#include "MyQTextEdit.h"
#include <QTimerEvent>
struct MyQTextEditPrivate
{
    MyQTextEditPrivate()
        :_PlaySpeed(1)
        ,_Text()
        ,_timer(0)
        ,_size(0)
        ,_PlayState(false)
    {
    }
    int         _PlaySpeed;
    QString     _Text;
    int         _timer;
    int         _size;
    bool        _PlayState;
};

MyQTextEdit::MyQTextEdit(QWidget *parent)
    :QTextEdit(parent)
    ,_p(new MyQTextEditPrivate)
{

}

MyQTextEdit::~MyQTextEdit()
{
    delete _p;
}

void MyQTextEdit::SetPlaySpeed(int speed)
{
    _p->_PlaySpeed = speed;
    CancleTimer();
    CreateTimer(1000/speed);
}

void MyQTextEdit::SetText(QString text)
{
    clear();
    _p->_Text = text;
}

void MyQTextEdit::ApendText(QString appendText)
{
    _p->_Text = _p->_Text + appendText;
}

bool MyQTextEdit::CreateTimer(int k)
{
    try{
        if(!_p->_timer)
        {
            _p->_timer = startTimer(k);
        }
        return true;
    }
    catch(...)
    {
        return false;
    }
}

bool MyQTextEdit::CancleTimer()
{
    if (_p->_timer)
    {
        killTimer(_p->_timer);
        _p->_timer = 0;
        return true;
    }
    return false;
}

void MyQTextEdit::CleanEdit()
{
    _p->_Text = "";
    _p->_size = 0;
    clear();
}

void MyQTextEdit::SetPause(bool state)
{
    _p->_PlayState = state;
}

void MyQTextEdit::timerEvent(QTimerEvent *event)
{
   //timerEvent(event);
    if(event->timerId() == _p->_timer)
    {
        if(_p->_Text.size() >= _p->_size)
        {
            //_p->_size += _p->_PlaySpeed;
            _p->_size += 1;
            if(_p->_Text.size() < _p->_size)
            {
                setText(_p->_Text);
            }
            else
            {
                setText(_p->_Text.mid(0,_p->_size - 1));
            }

        }
    }
}
